package com.example.dongshihao.startproject_211dsh.model;

import com.example.dongshihao.startproject_211dsh.MainActivity;
import com.example.dongshihao.startproject_211dsh.bean.WeatherResult;
import com.example.dongshihao.startproject_211dsh.iface.WeatherListener;
import com.example.dongshihao.startproject_211dsh.iface.Weatheriface;
import com.example.dongshihao.startproject_211dsh.service.WeatherService;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by dongshihao on 17/3/14.
 */

public class WeatherModel implements Weatheriface{
    private Retrofit retrofit;
    private String BASEURL="http://www.weather.com.cn/";
    private WeatherService weatherService;
    //retrofit1
    public WeatherModel() {
        System.out.println("---WeatherModel");
        retrofit=new Retrofit.Builder().baseUrl(BASEURL)
                .addConverterFactory(GsonConverterFactory.create()).build();

    }



    @Override
    public void getWeather(String cityno, final WeatherListener weatherListener) {
        System.out.println("---getWeather");
        //2
        weatherService=retrofit.create(WeatherService.class);
        Call<WeatherResult>  call=weatherService.getResult(cityno);
        //3
        call.enqueue(new Callback<WeatherResult>() {
            @Override
            public void onResponse(Call<WeatherResult> call, Response<WeatherResult> response) {
                //WeatherListener listener;
                System.out.println("---onResponse");
                if(response.isSuccessful() && response.body()!=null)
                    weatherListener.onRespense(response.body().getWeatherinfo());
                else
                    weatherListener.onFail("onresponse fail");
            }

            @Override
            public void onFailure(Call<WeatherResult> call, Throwable t) {
                System.out.println("---onFailure");
                weatherListener.onFail(t.toString());

            }
        });
    }
}